/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 */
package com.joolun.web.api;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.weixin.entity.LoginMaDTO;
import com.joolun.weixin.entity.WxOpenDataDTO;
import com.joolun.weixin.entity.WxUser;
import com.joolun.weixin.service.WxUserService;
import com.joolun.weixin.utils.ThirdSessionHolder;
import com.joolun.weixin.utils.WxMaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信用户
 *
 * @author www.joolun.com
 * @date 2019-08-25 15:39:39
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/api/ma/wxuser")
@Api(value = "wxuser", tags = "小程序用户API")
public class WxUserApi {

	private final WxUserService wxUserService;

	/**
	 * 小程序用户登录
	 *
	 * @param request
	 * @param loginMaDTO
	 * @return
	 */
	@ApiOperation(value = "小程序用户登录")
	@PostMapping("/login")
	public AjaxResult login(HttpServletRequest request, @RequestBody LoginMaDTO loginMaDTO) {
		try {
			WxUser wxUser = wxUserService.loginMa(WxMaUtil.getAppId(request), loginMaDTO.getJsCode());
			return AjaxResult.success(wxUser);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error(e.getMessage());
		}
	}

	@ApiOperation(value = "获取微信手机号")
	@PostMapping("/getWxPhone")
	public AjaxResult getWxPhone(@RequestBody LoginMaDTO loginMaDTO) {
		String appId = "wxcee27115c6ccdae7";
		String secret = "3b71c4ead2d8dd7cfa1645ad18b87b07";
		// 获取token
		String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, secret);
		JSONObject token = JSONUtil.parseObj(HttpUtil.get(token_url));
		// 使用前端code获取手机号码 参数为json格式
		String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getStr("access_token");
//		Map<String, Object> paramMap = new HashMap<>();
//		paramMap.put("code", loginMaDTO.getJsCode());
//		String phoneRes = HttpUtil.post(url, paramMap, 10000);
		String phone = null;
		System.out.println("code::::" + loginMaDTO.getJsCode());
		JSONObject body = new JSONObject();
		body.put("code", loginMaDTO.getJsCode());
		String ret = httpPostRaw(url, body.toString(), null, null);
		if (ret != null && !"".equals(ret)) {
			JSONObject json = JSONUtil.parseObj(ret);
			JSONObject phone_info = json.getJSONObject("phone_info");
			System.out.println("phone_info::" + phone_info);
			phone = phone_info.getStr("phoneNumber");
		}
		return AjaxResult.success(phone);
	}

	/**
	 * 获取用户信息
	 *
	 * @param
	 * @return
	 */
	@ApiOperation(value = "获取用户信息")
	@GetMapping
	public AjaxResult get() {
		String id = ThirdSessionHolder.getThirdSession().getWxUserId();
		return AjaxResult.success(wxUserService.getById(id));
	}

	/**
	 * 保存用户信息
	 *
	 * @param wxOpenDataDTO
	 * @return
	 */
	@ApiOperation(value = "保存用户信息")
	@PostMapping
	public AjaxResult saveOrUptateWxUser(@RequestBody WxOpenDataDTO wxOpenDataDTO) {
		wxOpenDataDTO.setAppId(ThirdSessionHolder.getThirdSession().getAppId());
		wxOpenDataDTO.setUserId(ThirdSessionHolder.getThirdSession().getWxUserId());
		wxOpenDataDTO.setSessionKey(ThirdSessionHolder.getThirdSession().getSessionKey());
		WxUser wxUser = wxUserService.saveOrUptateWxUser(wxOpenDataDTO);
		return AjaxResult.success(wxUser);
	}

	@ApiOperation(value = "修改用户信息")
	@PostMapping("editUser")
	public AjaxResult editUser(@RequestBody WxUser entity) {
		wxUserService.updateById(entity);
		return AjaxResult.success();
	}

	/**
	 * 参数以raw的方式做post请求
	 *
	 * @param url
	 * @param stringJson
	 * @param headers
	 * @param encode
	 * @return
	 */
	public static String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode) {
		String str = "";
		if (encode == null) {
			encode = "utf-8";
		}
		// HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		HttpPost httpost = new HttpPost(url);

		// 设置header
		httpost.setHeader("Content-type", "application/json");
		if (headers != null && headers.size() > 0) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httpost.setHeader(entry.getKey(), entry.getValue());
			}
		}
		// 组织请求参数
		StringEntity stringEntity = new StringEntity(stringJson, encode);
		httpost.setEntity(stringEntity);
		String content = null;
		CloseableHttpResponse httpResponse = null;
		try {
			// 响应信息
			httpResponse = closeableHttpClient.execute(httpost);
			HttpEntity entity = httpResponse.getEntity();
			content = EntityUtils.toString(entity, encode);
			System.out.println(content);
			str = content;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpResponse.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try { // 关闭连接、释放资源
			closeableHttpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
}
